package me.jiatao.paging2.paging2

import android.util.Log
import androidx.paging.PageKeyedDataSource
import kotlinx.coroutines.*
import me.jiatao.paging2.network.HttpRepository
import me.jiatao.paging2.pojo.ArticleItem

class ProjectDataSource : PageKeyedDataSource<Int, ArticleItem>() {
    private val ioScope = MainScope()
    private val startIndex = 1
    override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, ArticleItem>) {
        ioScope.launch {
            val projectPage = HttpRepository.getProjectList(startIndex)
            projectPage?.datas?.apply {
                callback.onResult(this, null, startIndex + 1)
            }
        }
    }

    override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, ArticleItem>) {
        Log.i("ProjectDataSource", "loadBefore-->" + params.key);
    }

    override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, ArticleItem>) {
        println("---------->${params.key}")

        ioScope.launch {
            val projectPage = HttpRepository.getProjectList(params.key)
            projectPage?.datas?.apply {
                callback.onResult(this, params.key + 1)
            }
        }
    }

}